var express = require('express');
var router = express.Router();
const multiparty = require("multiparty");
const path = require("path");
const { uploadFile, deleteFile, listFiles } = require("../utils/weixin_utils");
const fs = require("fs");

router.get('/', function(req, res, next) {
  res.render('login.html');
});

router.get('/detail', function(req, res, next) {
  res.render('detail.html');
});

router.get('/upfile', function(req, res, next) {
  res.render('upfile.html');
});

// router.get('/blank', function(req, res, next) {
//   res.render('blank.html');
// });

router.get('/viewer', function(req, res, next) {
  
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Credentials", true); 
    res.render('viewer.html');
    // res.send("123");
  });

router.post("/upload", function (req, res) {
  var form = new multiparty.Form({
      uploadDir: "./public/pdf",
      maxFieldsSize: 1024 * 1024 * 10
  
  });

  form.parse(req, async function (err, fields, files) {
      if (err) {
          res.send(err);
      } else {
          console.log("fields",fields);
          let newPath = files.file[0].path.substring(
            files.file[0].path.indexOf("pdf")
          );
          if(fields.id){
            newPath = fields.id + path.extname(newPath);
          }
          // console.log("upfile","/bankpdf/" + path.basename(newPath),files.file[0].path);
          // let result = {status:1};
          
          
          let result = await uploadFile(
              "/bankpdf/" + path.basename(newPath),
              files.file[0].path
          );
          fs.unlink(files.file[0].path,() => {});
          // console.log("result",result);
          if (result.status == 1) {
              res.send({ status: 1 , filename: result.url});
          } else {
              res.send({ status: 0 });
          }
      }
  });
});
module.exports = router;
